<template>
  <div class="common-wrapper">
    <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="12">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="选择部门" prop="department">
                <div style="display:flex;">
                  <a-button style="margin: 0 20px;" type="primary" @click="selectAll">全部部门</a-button>
                  <a-tree-select
                    @change="handleChange"
                    multiple
                    v-model="form.department"
                    style="width: 150px;"
                    :dropdown-style="{ maxHeight: '400px',  overflow: 'auto' }"
                    placeholder="请选择部门"
                    allow-clear
                    :tree-default-expand-all="false"
                    :treeData="departmentList"
                    :replaceFields="{children:'childs', title:'dep_name', key:'pkey', value: 'pkey' }"
                  >
                  </a-tree-select>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="工种">
              <a-select @change="workChange" v-model="form.work_type" mode="multiple" style="width: 185px">
                <a-select-option v-for="item in workList" :key="item.data_value">
                  {{ item.data_name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            </a-col>
          </a-row>
          <a-form-model-item label="选择移除人员" required>
            <a-transfer
              :data-source="staffList"
              :target-keys="targetKeys"
              :filter-option="(inputValue, item) => item.person_name.indexOf(inputValue) !== -1"
              :show-select-all="false"
              :showSearch="true"
              @change="onChange"
              :locale="locale"
              :titles="titles"
              :rowKey="(record) => record.person_idcard"
            >
              <template
                slot="children"
                slot-scope="{
                  props: { direction, filteredItems, selectedKeys },
                  on: { itemSelectAll, itemSelect },
                }"
              >
                <a-table
                  :row-selection="getRowSelection({ direction, selectedKeys, itemSelectAll, itemSelect, filteredItems})"
                  :columns="columns"
                  :dataSource="filteredItems"
                  :pagination="false"
                  size="small"
                  :scroll="{ y: 475 }"
                  :rowKey="(record) => record.person_idcard"
                />
              </template>
            </a-transfer>
          </a-form-model-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-model-item label="选择日期段" prop="date">
            <a-range-picker @change="onDateChange" style="width: 300px" />
          </a-form-model-item>
          <a-form-model-item label="选择班制" required>
            <a-button type="primary" :disabled="!hasSelected" @click="openModel">
              批量设置班制
            </a-button>
            <a-table
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
              :columns="planColumns"
              :pagination="false"
              :data-source="subParams.plans"
              size="small"
              :scroll="{ y: 540 }"
              :rowKey="(record) => record.plan_date"
            >
              <template slot="week" slot-scope="text, record">
                <span>{{ record.plan_date | weekFilter }}</span>
              </template>
              <template slot="class" slot-scope="text, record">
                <a-select style="width:180px;" v-model="record.class_key">
                  <a-select-option v-for="(item, key) of planList" :key="key" :value="key">
                    {{ item }}
                  </a-select-option>
                </a-select>
              </template>
            </a-table>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-form-model-item style="margin-top:20px;">
        <a-button type="primary" @click="onSubmit" :loading="loading">
          生成排班表
        </a-button>
        <a-button style="margin-left: 10px;" @click="resetForm">
          清空
        </a-button>
      </a-form-model-item>
    </a-form-model>
    <!-- 修改排班 -->
    <a-modal title="设置班制" :visible="visiblePlan" @cancel="handleCancelPlan">
      <span>选择班制：</span>
      <a-select v-model="class_key" style="width: 400px;margin:20px auto;">
        <a-select-option v-for="(item, key) of planList" :key="key" :value="key">
          {{key}}-{{ item }}
        </a-select-option>
      </a-select>
      <template slot="footer">
        <a-button @click="handleCancelPlan">取消</a-button>
        <a-button type="primary" @click="submitPlan">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script>
import difference from 'lodash/difference'
import { getAllDate } from '@/utils/util'
import { getStaffList, getDepartmentList, batchsetplan, getClassSelect, getDatadictionary } from '@/api/plan'
import { getPeopleListApi } from '@/api/people'
export default {
  data () {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      visiblePlan: false,
      form: {
        department: [],
        date: [],
        work_type: []
      },
      rules: {
        department: [{ required: true, validator: this.handleDepartment, trigger: 'blur' }],
        date: [{ required: true, message: '请选择日期段', trigger: 'blur' }]
      },
      departmentList: [],
      workList: [],
      staffList: [],
      staffListParams: {
        page_index: 1,
        page_size: 10000,
        department_names: '',
        work_types: ''
      },
      targetKeys: [],
      columns: [
        {
          dataIndex: 'person_name',
          title: '员工姓名'
        },
        {
          dataIndex: 'person_idcard',
          title: '工号'
        }
      ],
      locale: {
        itemUnit: '人',
        searchPlaceholder: '请输入员工姓名'
      },
      titles: ['已选定人员', '移除人员'],
      subParams: {
        person_ids: [],
        plans: []
      },
      planList: [],
      selectedRows: [],
      selectedRowKeys: [],
      planColumns: [
        {
          dataIndex: 'plan_date',
          align: 'center',
          title: '日期'
        },
        {
          title: '星期',
          align: 'center',
          scopedSlots: { customRender: 'week' }
        },
        {
          title: '班制名称',
          align: 'center',
          scopedSlots: { customRender: 'class' }
        }
      ],
      class_key: '',
      loading: false
    }
  },
  filters: {
    weekFilter (value) {
      var dateArray = value.split("-");
      var date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
      return "日一二三四五六".charAt(date.getDay());
    }
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0;
    }
  },
  mounted () {
    this.getDepartmentList()
    this.getPlanList()
    this.getWorkList()
  },
  methods: {
    handleDepartment (rule, value, callback) {
      if (this.staffList.length === 0) {
        return callback(new Error('请选择部门'))
      } else {
        return callback()
      }
    },
    // 选择全部部门
    async selectAll () {
      this.staffListParams.department_names = ''
      const { data } = await getStaffList(this.staffListParams)
      for (let i = 0; i < data.items.length; i++) {
        data.items[i].key = data.items[i].person_idcard
        data.items[i].title = data.items[i].person_idcard
      }
      this.staffList = data.items
      this.form.department = []
    },
    // 获取部门列表
    async getDepartmentList () {
      const { data } = await getDepartmentList()
      this.departmentList = data
    },
    // 获取工种列表
    async getWorkList() {
      const { data } = await getDatadictionary({ data_type: 3 })
      this.workList = this.workList.concat(data)
    },
    // 选择部门
    async handleChange (value) {
      this.staffListParams.department_names = `${value}`
      if (!this.staffListParams.department_names) {
        this.staffList = []
        return
      }
      const { data } = await getStaffList(this.staffListParams)
      for (let i = 0; i < data.items.length; i++) {
        data.items[i].key = data.items[i].person_idcard
        data.items[i].title = data.items[i].person_idcard
      }
      this.staffList = data.items
    },
    // 选择工种
    async workChange() {
      let work_types = this.form.work_type.join(',')
      this.staffListParams.work_types = work_types
      const { data } = await getPeopleListApi(this.staffListParams)
      for (let i = 0; i < data.items.length; i++) {
        data.items[i].key = data.items[i].person_idcard
        data.items[i].title = data.items[i].person_idcard
      }
      this.staffList = data.items
    },
    // 选择日期段
    onDateChange (date, dateString) {
      this.form.date = date
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.subParams.plans = getAllDate(dateString[0], dateString[1])
    },
    onChange (nextTargetKeys) {
      this.targetKeys = nextTargetKeys
    },
    getRowSelection ({ direction, selectedKeys, itemSelectAll, itemSelect, filteredItems }) {
      if (direction === 'left') {
        const selectArr = []
        filteredItems.forEach(item => {
          selectArr.push(item.pkey)
        });
        this.subParams.person_ids = selectArr
      }
      return {
        getCheckboxProps: item => ({ props: {} }),
        onSelectAll (selected, selectedRows) {
          const treeSelectedKeys = selectedRows.map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect ({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys
      }
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 获取班次下拉框
    async getPlanList () {
      const { data } = await getClassSelect()
      this.planList = data
    },
    openModel () {
      this.visiblePlan = true
    },
    handleCancelPlan () {
      this.class_key = ''
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.visiblePlan = false
    },
    submitPlan () {
      this.subParams.plans.forEach(item => {
        this.selectedRows.forEach(item1 => {
          if (item1.plan_date === item.plan_date) {
            item.class_key = this.class_key
          }
        })
      })
      this.selectedRows = [];
      this.class_key = ''
      this.selectedRowKeys = [];
      this.visiblePlan = false
    },
    onSubmit () {
      console.log(this.form)
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          for (let index = 0; index < this.subParams.plans.length; index++) {
            if (this.subParams.plans[index].class_key === '') {
              this.$message.error('请设置班制！')
              return
            }
          }
          this.loading = true
          const { succeeded } = await batchsetplan(this.subParams)
          if (succeeded) {
            this.$message.success('操作成功！')
            this.staffList = []
            this.subParams.plans = []
            this.$refs.ruleForm.resetFields();
            this.loading = false
          } else {
            this.$message.error('操作失败！')
            this.loading = false
          }
        } else {
          return false;
        }
      });
    },
    resetForm () {
      this.staffList = []
      this.subParams.plans = []
      this.$refs.ruleForm.resetFields();
    }
  }
}
</script>
<style scoped lang='less'>
.common-wrapper {
  height: 100%;
  padding: 20px;
}
</style>
